import { useCounterStore } from '@/stores/index.js';
const url = import.meta.env.VITE_WS;

class EnhancedWS {
    static instance = null;
    $ws = null;
    wsUrl = url;
    timeout = 30000;
    reconnectTimer = null;
    reconnectAttempts = 0;
    maxReconnectAttempts = 10;
    connected = false;
    heartbeatInterval = null;
    isManualClose = false; // 标记是否为手动关闭

    constructor() {
        if (EnhancedWS.instance) return EnhancedWS.instance;
        EnhancedWS.instance = this;
        this.initEventListeners();
    }

    initEventListeners() {
        window.addEventListener('beforeunload', () => {
            this.isManualClose = true;
            this.cleanup();
        });
        window.addEventListener('load', () => {
            this.isManualClose = false;
            this.tryReconnect();
        });
    }

    createWS() {
        // 清理现有连接
        this.cleanupExistingConnection();

        const token = localStorage.getItem('token');
        if (!token) return;

        const wsUrl = `${this.wsUrl}?token=${token}&paramterType=user&id=110`;
		console.log('wsUrl',wsUrl)
        this.$ws = new WebSocket(wsUrl);

        this.$ws.onopen = () => {
            this.connected = true;
            this.reconnectAttempts = 0;
            this.startHeartbeat();
            console.log('WebSocket connected');
        };

        this.$ws.onmessage = (msg) => {
            if (msg.data === 'PONG') return;
            try {
                const res = JSON.parse(msg.data);
				
                if (res.code === 'pound_weight') {
					
                    useCounterStore().updatePoundRealTime(res.message);
					useCounterStore().updateInfoObj(res.message);
                } 
            } catch (e) {
                console.error('Message parse error:', e);
            }
        };

        this.$ws.onclose = () => {
            this.connected = false;
            if (!this.isManualClose) {
                this.scheduleReconnect();
            }
        };

        this.$ws.onerror = (err) => {
            console.error('WebSocket error:', err);
            if (!this.isManualClose) {
                this.scheduleReconnect();
            }
        };
    }

    cleanupExistingConnection() {
        if (this.$ws) {
            // 移除事件监听器避免内存泄漏
            this.$ws.onopen = null;
            this.$ws.onmessage = null;
            this.$ws.onclose = null;
            this.$ws.onerror = null;
            
            // 关闭现有连接
            if (this.$ws.readyState === WebSocket.OPEN || 
                this.$ws.readyState === WebSocket.CONNECTING) {
                this.$ws.close();
            }
            this.$ws = null;
        }
        
        // 清除心跳
        clearInterval(this.heartbeatInterval);
        this.heartbeatInterval = null;
    }

    startHeartbeat() {
        this.heartbeatInterval = setInterval(() => {
            if (this.$ws?.readyState === WebSocket.OPEN) {
                this.$ws.send('PING');
            }
        }, this.timeout);
    }

    scheduleReconnect() {
        if (this.reconnectAttempts >= this.maxReconnectAttempts) return;

        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = setTimeout(() => {
            this.reconnectAttempts++;
            console.log(`Attempting reconnect #${this.reconnectAttempts}`);
            this.createWS();
        }, Math.min(1000 * 2 ** this.reconnectAttempts, 30000));
    }

    wsClose() {
        this.isManualClose = true;
        this.cleanup();
    }

    tryReconnect() {
        if (localStorage.getItem('token') && !this.connected && !this.isManualClose) {
            this.createWS();
        }
    }

    cleanup() {
        // 清除所有定时器
        clearInterval(this.heartbeatInterval);
        this.heartbeatInterval = null;
        
        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = null;
        
        // 清理现有连接
        this.cleanupExistingConnection();
    }
}

export default new EnhancedWS();